<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import moment from "moment"
// import { cardDataLoad, boardLoad } from '@/api/share'
var defaultData = [
    {
        value: [4200, 3000, 20000, 35000, 50000, 18000],
        name: '系列1'
    },
    {
        value: [5000, 14000, 28000, 26000, 42000, 21000],
        name: '系列2'
    }];
var defaultItem = [
    { name: '分类1', max: 6500 },
    { name: '分类2', max: 16000 },
    { name: '分类3', max: 30000 },
    { name: '分类4', max: 38000 },
    { name: '分类5', max: 52000 },
    { name: '分类6', max: 25000 }
];

export default {
    Name: "Radar",
    components: {
        echarts
    },
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            showContent: false,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            filterForm: {
                pageInfo: {
                    pageSize: 1,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
            timer: null,
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        reloadInfo() {
            var self = this;

            // 重绘
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            // #region
            const end = new Date();
            const start = new Date();
            if (this.obj.tableData.type == 0) {
                this.filterForm.isOnlie = true;

                // 查询一天内数据
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                this.filterForm.beginTime = this.parseTime(start);
                this.filterForm.endTime = this.parseTime(end);
            } else {
                this.filterForm.isOnlie = false;

                start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d}");
                this.filterForm.endTime = this.parseTime(end);

                // 刷新时间兼容处理
                if (timeSize < 60) {
                    timeSize = 60;
                }
            }
            // #endregion

            clearInterval(this.timer);

            this.getLineData((dataResult) => {
                var data = self.resultDataToObject(dataResult);
                self.setOptions(data.data, data.item);
            });

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end);

                    this.getLineData((dataResult) => {
                        var data = self.resultDataToObject(dataResult);
                        self.setOptions(data.data, data.item);
                    });
                }, timeSize * 1000);
            }
        },
        // 数据转换
        resultDataToObject(dataResult) {
            var serveData = [];
            var defaultItem = this.obj.tableData.barList;

            // var defaultData = [
            //     {
            //         value: [4200, 3000, 20000, 35000, 50000, 18000],
            //         name: '系列1'
            //     },
            //     {
            //         value: [5000, 14000, 28000, 26000, 42000, 21000],
            //         name: '系列2'
            //     }];

            var self = this;
            if (dataResult.dataList && dataResult.columns) {
                var dataList = dataResult.dataList.reverse();

                dataList.forEach((x, j) => {
                    serveData.push({ name: x[0], value: x.slice(1) });
                });
            }

            return {
                item: defaultItem,
                data: serveData
            }
        },
        setStyle() {
            var style = this.obj.style;

            // #region 组件背景图或颜色
            var backgroundColor = "";
            var backgroundImage = "";

            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "";
            }
            // #endregion

            // #region 组件投影
            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }
            // #endregion

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                // backgroundImage,
                // backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions(valData, columns) {
            var self = this;

            // #region 网格文字颜色
            var color = "#333333";
            if (this.obj.tableData.color) {
                color = this.obj.tableData.color;
            }
            var lineColor = "#eeeeee"
            if (this.obj.tableData.lineColor) {
                lineColor = this.obj.tableData.lineColor;
            }
            // #endregion

            columns.forEach(e => {
                e.color = color;
            })

            // #region 系列颜色
            var colors = ['#fc8251', '#5470c6', '#91cd77', '#ef6567', '#f9c956', '#75bedc'];
            var newColors = [];
            if (this.obj.tableData.colors) {
                newColors = this.obj.tableData.colors;
            } else {
                newColors = newColors.concat(colors);
            }

            var lineColor = "#eeeeee"
            if (this.obj.tableData.lineColor) {
                lineColor = this.obj.tableData.lineColor;
            }
            // #endregion

            // #region 图例 legend样式
            var isShowLegend = true;
            if (this.obj.tableData.isShowLegend != undefined) {
                isShowLegend = this.obj.tableData.isShowLegend;
            }
            var icon = "circle";
            if (this.obj.tableData.icon) {
                icon = this.obj.tableData.icon;
            }

            var textColor = "#333333";
            if (this.obj.tableData.textColor) {
                textColor = this.obj.tableData.textColor;
            }
            var textFontsize = '14px';
            if (this.obj.tableData.textfontSize) {
                textFontsize = this.obj.tableData.textfontSize + "px";
            }
            var textFontWeight = "";
            if (this.obj.tableData.textFontWeight) {
                textFontWeight = this.obj.tableData.textFontWeight;
            }
            var textFontStyle = "";
            if (this.obj.tableData.textFontStyle) {
                textFontStyle = this.obj.tableData.textFontStyle;
            }

            // #endregion

            // #region 标签样式
            var symbolSize = 5;
            var decimal = 0;
            if (this.obj.tableData.decimal) {
                decimal = this.obj.tableData.decimal;
            }

            var isShowLabel = false;
            if (this.obj.tableData.isShowValue) {
                isShowLabel = this.obj.tableData.isShowValue;
            }
            var valColor = "#333333";
            if (this.obj.tableData.valueColor) {
                valColor = this.obj.tableData.valueColor;
            }
            var valFontsize = '14px';
            if (this.obj.tableData.valuefontSize) {
                valFontsize = this.obj.tableData.valuefontSize + "px";
            }
            var valFontWeight = "";
            if (this.obj.tableData.valueFontWeight) {
                valFontWeight = this.obj.tableData.valueFontWeight;
            }
            var valFontStyle = "";
            if (this.obj.tableData.valueFontStyle) {
                valFontWeight = this.obj.tableData.valueFontStyle;
            }
            // #endregion

            this.chart.setOption({
                grid: {
                    left: "4%",
                    right: "4%",
                    top: "60px",
                    bottom: "20px",
                    containLabel: true
                },
                color: newColors,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    top: "25px",
                    left: "15px",
                    show: isShowLegend,
                    // orient: orient,
                    right: 10,
                    textStyle: {
                        color: textColor,
                        fontSize: textFontsize,
                        fontWeight: textFontWeight,
                        fontStyle: textFontStyle,
                    },
                    icon,
                    formatter: (val) => {
                        return val;
                    }
                },
                radar: {
                    // shape: 'circle',
                    indicator: columns
                },
                series: [{
                    type: 'radar',
                    data: valData,
                    label: {
                        show: isShowLabel,
                        position: "inside",
                        formatter: function (param) {
                            return Number(param.value).toFixed(decimal);
                        },
                        color: valColor,
                        fontSize: valFontsize,
                        fontWeight: valFontWeight,
                        fontStyle: valFontStyle,
                    },
                    symbol: this.obj.tableData.symbol,
                    symbolSize: symbolSize,
                    lineStyle: {
                        width: 1,
                    }
                },],
            });

            return false;



            // #region 标签样式
            var decimal = 0;
            if (this.obj.tableData.decimal) {
                decimal = this.obj.tableData.decimal;
            }

            var isShowLabel = false;
            if (this.obj.tableData.isShowValue) {
                isShowLabel = this.obj.tableData.isShowValue;
            }
            var valColor = "#333333";
            if (this.obj.tableData.valueColor) {
                valColor = this.obj.tableData.valueColor;
            }
            var valFontsize = '14px';
            if (this.obj.tableData.valuefontSize) {
                valFontsize = this.obj.tableData.valuefontSize + "px";
            }
            var valFontWeight = "";
            if (this.obj.tableData.valueFontWeight) {
                valFontWeight = this.obj.tableData.valueFontWeight;
            }
            var valFontStyle = "";
            if (this.obj.tableData.valueFontStyle) {
                valFontWeight = this.obj.tableData.valueFontStyle;
            }
            // 标签位置
            var lablePosition = undefined;
            if (this.obj.tableData.lablePosition) {
                lablePosition = this.obj.tableData.lablePosition;

                if (this.obj.tableData.isZong) {
                    if (this.obj.tableData.lablePosition == "insideTop") {
                        lablePosition = "insideRight";
                    } else if (this.obj.tableData.lablePosition == "top") {
                        lablePosition = "right";
                    }
                }
            }
            // #endregion

            //  #region 数据 图形
            var seriesData = [];
            columns.forEach((x, i) => {
                var item = {
                    type: 'radar',
                    stack: this.obj.tableData.iSstack,
                    name: x,
                    data: actualData[i],
                    // barWidth: "30",
                    showBackground: this.obj.tableData.showBackground,
                    backgroundStyle: {
                        color: this.obj.tableData.backgroundStyleColor
                    },
                    label: {
                        show: isShowLabel,
                        position: lablePosition,
                        formatter: function (param) {
                            return Number(param.value).toFixed(decimal);
                        },
                        color: valColor,
                        fontSize: valFontsize,
                        fontWeight: valFontWeight,
                        fontStyle: valFontStyle,
                    },
                };
                seriesData.push(item);
            })
            // #endregion


        },
        getLineData(callback) {

            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;

                this.setOptions(defaultData, defaultItem);
                return false;
            }
            // #endregion

            // #region 参数不完整
            var idlist = [this.obj.tableData.xId];
            if (this.obj.tableData.barList.length == 0) {
                this.showContent = false;
                return false;
            }
            this.obj.tableData.barList.forEach(e => {
                if (e.id) {
                    idlist.push(e.id);
                }
            });
            if (idlist.length - 1 != this.obj.tableData.barList.length) {
                this.showContent = false;
                return false;
            }
            // #endregion

            this.showContent = true;
            this.filterForm.tableId = this.obj.tableData.tableId;
            this.filterForm.pageInfo.pageSize = this.obj.tableData.count;
            this.filterForm.structureIds = idlist;

            if (this.obj.tableData.type != 1) {
                cardDataLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            } else {
                boardLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            }
        }
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>